<?php

namespace unifiedpay\plugins\lib;

class WoaizfClient
{
	private $apiurl = 'https://payapi.52zhifu.com/';
	private $appid;
	private $appkey;

	function __construct($config){
		$this->appid = $config['appid'];
		$this->appkey = $config['appkey'];
		if(!empty($config['apiurl'])) {
			$this->apiurl = $config['apiurl'];
		}
	}

	//创建支付订单
	public function payment_create($params){
		$path = 'api/payment/create';
		return $this->execute($path, $params);
	}

	//订单退款确认
	public function refund_confirm($params){
		$path = 'api/refund/confrim';
		return $this->execute($path, $params);
	}

	//获取OPENID
	public function openid($redirect_uri){
		$url = $this->apiurl.'api/openid?appid='.$this->appid.'&redirect_uri='.urlencode($redirect_uri);
		return $url;
	}

	//通知回调验证
	public function verify($arr){
		if(!isset($arr['sign'])) return false;
		$sign = $this->make_sign($arr, $this->appkey);
		return $sign === $arr['sign'];
	}

	//发起代付转账订单
	public function trans_confirm($params){
		$path = 'api/trans/confrim';
		return $this->execute($path, $params);
	}

	//查询代付转账订单
	public function trans_query($trade_no){
		$path = 'api/trans/query';
		$params = [
			'trade_no' => $trade_no
		];
		return $this->execute($path, $params);
	}

	//发起通用请求
	public function execute($path, $params){
		$url = $this->apiurl.$path;
		$publicParams = [
			'appid' => $this->appid,
			'timestamp' => time(),
		];
		$params = array_merge($publicParams, $params);
		$params['sign'] = $this->make_sign($params, $this->appkey);
		$response = $this->getHttpResponse($url, http_build_query($params));
		$result = json_decode($response, true);
		if(isset($result['code']) && $result['code']==200){
			return isset($result['data']) ? $result['data'] : true;
		}else{
			throw new \Exception($result['message']?$result['message']:'返回数据解析失败');
		}
	}

	private function getHttpResponse($url, $post = false, $timeout = 10){
		$ch = curl_init($url);
		curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
		$httpheader[] = "Accept: */*";
		$httpheader[] = "Accept-Language: zh-CN,zh;q=0.8";
		$httpheader[] = "Connection: close";
		curl_setopt($ch, CURLOPT_HTTPHEADER, $httpheader);
		curl_setopt($ch, CURLOPT_HEADER, false);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		if($post){
			curl_setopt($ch, CURLOPT_POST, true);
			curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
		}
		$response = curl_exec($ch);
		curl_close($ch);
		return $response;
	}

	private function make_sign($param, $key){
		ksort($param);
		$signstr = '';
	
		foreach($param as $k => $v){
			if($k != "sign" && $v!=''){
				$signstr .= $k.'='.$v.'&';
			}
		}
		$signstr = substr($signstr,0,-1);
		$sign = md5($signstr.$key);
		return $sign;
	}
}
